<template>
  <div>
    <div class="p-2">
      <router-link to="/" tag="div" >
        <i class="iconfont icon-jiantou3 grey-1"></i>
      </router-link>
      <div class="mt-4  pl-login pr-login">
        <h2 class="font-login primary text-center">硅谷外卖</h2>
        <div class="mt-4">
          <div class="login-h text-center">
            <span class="font-xm black mr-5" @click="loginWay = true" :class="{active:loginWay}">短信登录</span>
            <span class="font-xm black" @click="loginWay = false" :class="{active:!loginWay}">密码登录</span>
          </div>
          <!-- 手机号 登录-->
          <div v-if="loginWay">
            <div class="login-b1 pt-2 text-center">
              <div class="phoneGet clearfix">
                <input type="text" placeholder="手机号" class="phone" v-model="model.phone">
                <button class="noCheck" :disabled="disabled" :class="{right_phone:rightPhone}" @click="getCode">{{computeTime>0 ? `已发送(${computeTime}s)` : '获取验证码'}}</button>
              </div>
              <input type="text" placeholder="验证码" class="check" v-model="model.code">
            </div>
            <div class="userTip">
              <span class="grey-1 font-xm">温馨提示：未注册硅谷外卖帐号的手机号，登录时将自动注册，且代表已同意</span>
              <a href="#" class="primary font-xm">《用户服务协议》</a>
            </div>
          </div>
          <!-- 密码登录 -->
          <div v-else>
            <div class="login-b1 pt-2 text-center">
              <input type="text" placeholder="手机/邮箱/用户名" class="phone" v-model="model1.name">
              <div class="phoneGet clearfix">
                <input type="text" placeholder="密码" class="phone" v-if="showPsw" v-model="model1.pwd">
                <input type="password" placeholder="密码" class="phone" v-else v-model="model1.pwd">
                <div class="changeBtn" @click="showPsw = !showPsw" :class="{bg_right:!showPsw,bg_left:showPsw}">
                  <div class="circle" :class="{right:showPsw,left:!showPsw}"></div>
                </div>
              </div>
              <div class="codeImg">
                <input type="text" placeholder="验证码" class="check" v-model="model1.captcha">
                <img ref="captcha" src="http://localhost:4000/captcha" alt="" style="width: 150px;height: 50px;" @click="getCaptcha()">
              </div>
            </div>
          </div>
          <div class="login-b2 mt-6 display-flex jc-center wrap">
            <button class="bg-green" @click="submit">登录</button>
            <span class="grey-1 font-m mt-2">关于我们</span>
          </div>
        </div>
      </div>
    </div>
    <AlertTip :alert-text="alertText" v-if="showAlert" @closeTip="closeTip"></AlertTip>
  </div>
</template>

<script>
  import AlertTip from "../../components/AlertTip/AlertTip";
  import {RECEIVE_USERINFO} from "../../store/mutation-types";
  export default {
    name: "Login",
    components:{
      AlertTip
    },
    data(){
      return {
        loginWay:true, //true表示短信登录 false表示密码登录
        disabled:true,
        computeTime:0,//计时的时间
        intervalId:null,
        showPsw:false, //是否显示密码
        model:{
          phone:'',  //手机号
          code:'',  //短信验证码
        },
        model1:{
          name:'',  //手机/邮箱/用户名
          pwd:'',   //密码
          captcha:''  //图形验证码
        },
        alertText: '',  //提示文本
        showAlert:false  //是否显示提示框
      }
    },
    computed:{
      //验证手机号是否正确
      rightPhone(){
        if(/^1\d{10}/.test(this.model.phone)){
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.disabled = false
          return true
        } else {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.disabled = true
          return false
        }
      }
    },
    methods:{
      //异步获取短信验证码
      async getCode(){
        //如果当前没有计时
        if (this.computeTime === 0){
          //启动倒计时
          this.computeTime = 30
          // setInterval() 方法会不停地调用函数，直到 clearInterval() 被调用或窗口被关闭。
          this.intervalId = setInterval(()=>{
            this.computeTime--
            if(this.computeTime === 0){
              clearInterval(this.intervalId)
            }
          },1000)
          // 发送请求（向指定手机号发送验证码短信）
          const {data:res} = await this.$http.get(`http://localhost:4000/sendcode`,this.model.phone)
          if (res.code === 1){
            //显示提示
            this.alertTextAndShow(res.msg)
            // 停止倒计时
            if(this.computeTime > 0){
              this.computeTime = 0;
              clearInterval(this.intervalId)
              this.intervalId = undefined
            }
          }
        }
      },
      //警告框的文本域显示
      alertTextAndShow(alertText){
        this.showAlert = true
        this.alertText = alertText
      },
      // 异步登录
      async submit() {
        let result
        //前台表单验证
        if (this.loginWay) {
          //短信登录
          const {code} = this.model
          if (!this.rightPhone) {
            //提示手机号不正确
            this.alertTextAndShow('手机号不正确')
            return
          } else if (!/^\d{6}$/.test(code)) {
            //验证码必须是六位数字，验证码不正确
            this.alertTextAndShow('验证码不正确')
            return
          }
          //发送短信登录请求
          result = this.$http.post(`http://localhost:4000/login_sms`, this.model)
        } else {
          //密码登录
          const {name, pwd, captcha} = this.model1
          if (!name) {
            //没有输入用户名
            this.alertTextAndShow('请输入用户名')
            return
          } else if (!pwd) {
            //密码必须填写
            this.alertTextAndShow('请输入密码')
            return
          } else if (!captcha) {
            //验证码必须填写
            this.alertTextAndShow('请输入验证码')
            return
          }
          //发送登录请求
          result = await this.$http.post(`http://localhost:4000/login_pwd`, this.model1)

          console.log(result)
        }
        //停止定时器
        if(this.computeTime > 0){
          this.computeTime = 0;
          clearInterval(this.intervalId)
          this.intervalId = undefined
        }
        //处理登录返回数据
        if (result.data.code === 0) {
          const user = result.data
          //将user保存到vuex的state中
          console.log(user)
          this.$store.commit(RECEIVE_USERINFO,user)
          //跳转路由
          this.getCaptcha()
          this.$router.replace('/person')
        } else {
          const msg = result.data.msg
          this.alertTextAndShow(msg)
          this.getCaptcha()
          this.model1={}
          this.model2={}
        }
      },
      //关闭警告框
      closeTip(){
        this.alertText = ''
        this.showAlert = false
      } ,
      //获取一个新的图片验证码
      getCaptcha(){
        //每次指定的src要不一样
        this.$refs.captcha.src = 'http://localhost:4000/captcha?time='+Date.now()
      }
    },

  }
</script>

<style lang="scss" scoped>
@import "../../assets/scss/variable";
@import "../../assets/common.css";
  .iconfont{
    font-size: 1.538rem;
  }
  .login-h{
    span {
      border-bottom: 2px solid transparent;

    }
    .active {
      padding-bottom: 2px;
      border-bottom: 2px solid map_get($colors,'primary');
      color: map_get($colors,'primary');
      font-weight: 700;
    }
  }
  .login-b1{
    position: relative;
    input{
      width: 100%;
      height: 3.692rem;
      margin-bottom: 12px;
      border: 1px solid map_get($colors,'grey');
      border-radius: 4px;
      padding-left: 8px;
      font-size: 1.077rem;
      &:focus{
        border: 1px solid map_get($colors,'primary')
      }
    }
    .phoneGet{
      position: relative;
      /*<!--noCheck{-->*/
      /*<!--  font-size: map_get($font-sizes,'xm');-->*/
      /*<!--  color: #02a774;-->*/
      /*<!--}-->*/
      &.right_phone{
        color: black;
      }
      button{
        position: absolute;
        right: 0;
        top: 23%;
      }
      .changeBtn{
        position: absolute;
        right: 0;
        top: 17px;
        width: 41px;
        height: 15px;
        border: 1px solid map_get($colors,'grey');
        border-radius: 15px;
        &.bg_right{
          background-color: #fff;
        }
        &.bg_left{
          background-color:map_get($colors,'primary')
        }
        .circle{
          position: absolute;
          box-shadow: 1px 1px map_get($colors,'grey') ;
          top: -1px;
          width: 15px;
          height: 15px;
          border-radius: 50%;
          background-color: #fff;
          border: 1px solid map_get($colors,'grey');
          z-index: 9;
          &.left{
            left: 0;
          }
          &.right {
            right: 0;
            /*transform: translateX(28px);*/
          }
        }

      }
    }
    .codeImg{
      position: relative;
      img{
        position: absolute;
        right: 0;
        top: 0;
      }
    }
    .userTip{
      span{
        text-align: right
      }
    }
  }
  .login-b2{
    button{
      width: 100%;
      height: 3.231rem;
      border-radius: 0.462rem;
      color: #ffffff;
      font-size: 1.231rem;
    }
    span {
      text-align: center;
    }
  }
</style>
